<template>
	<view class="page-container">
		<use-navbar ref="navbar" :show="false" :back="false" :bg-color="navbarBgcolor" :title="appslogan">
		</use-navbar>
		<!-- 启动界面 -->
		<view class="start-up-panel  w-full pos-f" style="height: 100vh;z-index: 10;">
			<view class="pos-f dflex-b" style="top:95px;right: 15px;left: 15px;">
				<view class="dflex-b" @click="clear">
					<!-- <uni-icons type="trash" color="#5e6d82" size="22" style="width: 25px;" />
					<text class="fs-23 ft-dark-3">退出</text> -->
				</view>
				<view class="border-radius-lg  padding-lr-sm padding-tb-xxs fs-23 ft-dark-4"
					style="background-color:rgba(80, 80, 80, 0.1);">
					<text>跳过</text><text class="padding-lr-xxs">{{ countdown }} 秒</text>
				</view>

			</view>
			<view class="panel-bg pos-f w-full" style="height: 100vh;z-index: 9;">
				<image src="https://saastest.youerp.cn/saas_N912d04/api/resources/images/bg.jpg" mode="scaleToFill">
				</image>
			</view>
			<view style="padding: 25vh 0;z-index: 10;" class="pos-r tac">
				<view class="padding-bottom-lg" style="">
					<text class="dblock fs-50">欢 迎 使 用 聚 管 事</text>
				</view>
				<text class="fs-30">我要做什么?</text>
			</view>

			<view class="pos-f w-full tac " style="bottom: 30rpx;">
				<text class="ft-dark-2 fs-25">Presented by 聚友大道 </text>
			</view>
		</view>
		<!-- 启动界面 结束-->
		<view class='home-area' style="display: none;">
			<view class='header'>
				<view class="dflex-b">
					<text></text>
					<uni-icons type="trash" color="#5e6d82" size="22" style="width: 25px;" @click="clear" />
				</view>
				<view style="height: 45px;"></view>
				<image src='@/static/logo.png' style="width: 150px;height: 150px;"></image>
			</view>
		</view>
		<view style="height: 16.5vh"></view>
		<use-popup mode="center" bgclass=" " close-icon :show="NetworkStatus">
			<view class="border-radius-top30 safe-area-inset-bottom">
				<view class="refresh tac padding-tb" @click="refresh">
					<view class="tips">
						<p>网络崩溃了</p>
						<span>重试</span>
					</view>
				</view>
			</view>
		</use-popup>
		<!-- 微信授权 -弹窗 -->
		<use-popup mode="center" bgclass=" " close-icon :show="showAuthorize">
			<view class="border-radius-top30 padding-sm">
				<view class="tac fwbd w-full padding-lr  padding-top padding-bottom fs-34">微信授权提醒
				</view>
				<view class="padding dflex-c padding-bottom">
					<text class="fs-30">请先授权获取微信信息</text>
				</view>
				<view class="dflex-c btns-area padding-top-sm">
					<view class="dflex-c padding-lr-sm  border-radius-lg wpre-30 margin-lr" @click="nixAuthorize">
						<text class="ft-dark-4 fs-28">拒绝</text>
					</view>
					<view class="dflex-c padding-lr-sm  border-radius-lg wpre-30 margin-lr" @click="onAuthorize">
						<text class="fs-28" style="color: #00abe0;">同意</text>
					</view>
				</view>
			</view>
		</use-popup>
	</view>
</template>
<script setup>
	// --组合式 API

	// --用户当前启用状态的监测，未定，？？？
	import {
		ref,
		computed,
		getCurrentInstance,
		watch,
		onMounted,
	} from 'vue';
	import {
		onLoad,
		onUnload,
		onShow,
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app";


	import {
		useUserStore
	} from '@/store'

	const {
		ctx,
		proxy
	} = getCurrentInstance();

	let UserStore = useUserStore();
	const navbarBgcolor = ref('#f5f5f5')
	const NetworkStatus = ref(false)
	const showAuthorize = ref(false)
	const timestamp = ref('')
	const wxUserInfo = ref({})
	// --测试用户信息
	const wxTestUserInfo = ref({
		unionid: 'osTq6s1TidzupwoesC70YWzGnsuE',
		openid: 'oj0r_5FDyP02H9-HhHieWujs02Ic'
	});
	const showMsg = (msg) => {
		proxy.$utils.msg('用户微信授权成功~');
	}
	const countdown = ref(2); // 初始化倒计时时间
	let timerId = null; // 定时器ID

	// onLoad 接受 A 页面传递的参数
	onLoad(async (option) => {
		console.log("index 页面 onLoad:", option);
		// --邀请判断,分享链接失效判断
		uni.$on("refresh", (e) => {
			console.log("需要重新访问一下接口"); //需要重新访问一下接口。
		})
		initStartUp();
	});

	onShow(async () => {
		console.log("onShow")
	});
	const initStartUp = async () => {
		//第一步获取unionID
		var wx = mpWeixinGetUserProfile();
		wx.then((res) => {
			console.log(res);
			// #ifdef H5
			wxUserInfo.value.unionid = res.unionid;
			wxUserInfo.value.openid = res.openid;
			// #endif
			// #ifdef  APP-PLUS || MP-WEIXIN
			wxUserInfo.value.unionid = res.wxInfo.unionid;
			wxUserInfo.value.openid = res.wxInfo.openid;
			// #endif

			uni.showLoading({
				title: "系统启动中..."
			})
			getUseMatrixInfo();
		});
		// #ifdef  APP-PLUS || MP-WEIXIN
		// wx.updateShareMenu({
		// 	withShareTicket: true,
		// 	success() {}
		// })
		// #endif
	}
	onUnload(() => {
		// 清除监听
		uni.$off('refresh');
	})
	const startCountdown = () => {
		countdown.value = 2; // 设置倒计时初始值
		timerId = setInterval(() => {
			countdown.value--; // 每秒减少1
			if (countdown.value === 1) {
				clearInterval(timerId); // 倒计时结束时清除定时器
			}
		}, 1000);
	};
	// 快捷获取用户数据
	const mpWeixinGetUserProfile = () => {
		let baseUrl = proxy.$config.baseUrl;
		var resu = {};
		return new Promise((resolve, reject) => {
			// #ifdef H5
			// --WEB端模拟微信登录
			console.log('WEB端模拟微信登录');
			resolve({
				unionid: wxTestUserInfo.value.unionid,
				openid: wxTestUserInfo.value.openid
			})
			// #endif
			// #ifdef  APP-PLUS || MP-WEIXIN
			uni.login({
				provider: 'weixin',
				onlyAuthorize: true,
				success: (res) => {
					if (res.errMsg == 'login:ok') {
						var url = baseUrl +
							'/webapi/saas_weixin_api.ashx?oper=miniProgram_login&code=' + res.code;
						uni.request({ //只要取openid
							url: url,
							data: {
								code: res.code,
								key: "0001"
							},
							success: mpres => {
								resolve(mpres.data)
							},
							fail: res => {
								proxy.$utils.msg(res);
							}
						})
					}
				},
			});
			// #endif 
		})
	};

	const refresh = () => {

	}
	// 进入系统的时候检测，用户身份，站点等信息
	const enterSystem = async (bool) => {
		console.log(bool);
		if (!bool) {
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/tabbar/index'
				});
			}, 1.75 * 1000)
			return;
		}
		if (!UserStore.member.member_id) {
			proxy.$utils.msg("当前用户在系统中不存在，请加入已有公司或创建新公司~");
			return false;
		}
		setTimeout(() => {
			uni.hideLoading();
			uni.switchTab({
				url: '/pages/tabbar/index'
			});
		}, 1.75 * 1000)
	}

	// -只检测用户缓存的登录信息，进入系统的时候检测，用户身份，站点等信息
	const checkLoginState = async () => {
		if (!UserStore.islogin || !wxUserInfo.value.unionid) {
			return false;
		} else return true;
	}
	/*
	 ** 模拟登录
	 */
	const simulationLogin = () => {
		// --模拟登录
		let datas = {
			member: {
				id: '',
				avatarUrl: '',
				member_name: 'rein',
				member_id: '7a4a2cd4-fcb5-4312-9cd6-54dd04f6ada7',
				member_access_token: "",
				member_mobile: '',
				member_nickname: '',
				member_weixin: 'osTq6s1TidzupwoesC70YWzGnsuE'
			},
			user: {
				uid: '7a4a2cd4-fcb5-4312-9cd6-54dd04f6ada7',
				token: "",
				tokenExpired: "",
				userInfo: {
					mobile: "",
					role: [], //--角色
					username: "rein",
					user_id: '7a4a2cd4-fcb5-4312-9cd6-54dd04f6ada7',
					avatarUrl: '',
					member_name: '',
					member_nickname: 'rein'
				}
			}
		}
		this.login(datas);
		this.$util.msg("模拟登录成功");
	}
	// 读取用户信息
	const getUseMatrixInfo = () => {
		loadData('P_SaaS_GetSiteUserInfo', false, (res) => {
			console.log("查询子服务器结果：", res)
			try {
				if (res.status == '1') {
					if (res.data1.length == 0) {
						proxy.$utils.msg('系统错误，获取用户信息失败~');
						return;
					}
					if (res.data1[0].status == '1' || res.data1[0].status == 'True') {
						var _userInfo = {
							member: {
								appid: proxy.$config.wxMpKey,
								member_id: res.data1[0].user_id,
								member_headimg: res.data1[0].userphoto,
								member_name: res.data1[0].user_name,
								member_nickname: res.data1[0].user_name,
								member_weixin: wxUserInfo.value.unionid,
								member_openid: wxUserInfo.value.openid,
								member_rid: res.data1[0].rid,
								member_access_token: '',
								family_id: res.data1[0].familyid,
								member_mobile: '',
								msgnum: res.data1[0].asknum,
								user_code: res.data1[0].code,
								ORG: '',
								ORGID: '',
								state: '',
								is_plus: ''
							},
							user: {
								uid: '',
								token: "",
								tokenExpired: "",
								userInfo: {
									mobile: '',
									role: ['member'],
									username: '',
									user_id: ''
								}
							}
						};
						UserStore.putMsgNum(res.data1[0].asknum);
						UserStore.login(_userInfo);

						// --成员列表未获取的先获取一边，备用,站点切换也需要重新读取组织成员数据
						console.log("获取成员列表");
						getMemberList();
						//如果退出登录就不自动进入
						if (!UserStore.islogin) {
							return;
						}
						proxy.$utils.timerout(() => {
							console.log("进入系统", countdown.value);
							// --启动计算器，并进入系统
							startCountdown();
							enterSystem(true);
						}, 250)
						return;
					}
					proxy.$utils.msg(res.data1[0].tips);
				}
				proxy.$utils.msg('系统错误，获取用户信息失败~');
			} catch (e) {
				console.log(e);
				uni.hideLoading();
				proxy.$utils.msg('系统错误');
			}
		})
	}

	const getMemberList = async () => {
		loadData('P_SaaS_FindUserbyFamily', '', (res) => {
			console.log("首次预加载成员列表：", res);
			try {
				if (res.status == '1') {
					let datas = [];
					if (res.data1 && res.data1.length > 0) {
						res.data1.forEach(x => {
							datas.push({
								_id: x.userid,
								avatarUrl: x.avatarurl,
								nickName: x.user_name,
								rid: x.rid,
								role: x.role,
								checked: false
							});
						});
						UserStore.putMemberList(datas);
					}
				}
			} catch (e) {
				//TODO handle the exception
			}
		})
	}
	const loadData = async (type, mode, callback) => {
		let param, _res;
		switch (type) {
			case 'P_SaaS_FindUserbyFamily':
				param = {
					storedPro: 'P_SaaS_FindUserbyFamily',
					paraNum: 3,
					resultSetNum: 1,
					para1: UserStore.member.member_id,
					para2: UserStore.member.family_id,
					para3: 'family'
				}
				_res = await getData(param);
				break;
			case 'P_SaaS_GetSiteUserInfo': // --获取用户信息
				param = {
					storedPro: 'P_SaaS_GetSiteUserInfo',
					paraNum: 3,
					resultSetNum: 1,
					para1: wxUserInfo.value.unionid,
					para2: '',
					para3: ''
				}
				_res = await getData(param);
				break;
			case 'P_Saas_CheckUserStatus': // 检测用户加入状态
				/*				 
				 */
				param = {
					storedPro: 'P_Saas_CheckUserStatus',
					paraNum: 3,
					resultSetNum: 1,
					para1: wxUserInfo.value.unionid,
					para2: Inviter.value.cId,
					para3: Inviter.value.mId
				}
				_res = await getData(param, false);
				break;
			default:
		}
		if (typeof callback === 'function') {
			// 数据加载完成回调函数
			callback(_res);
		}
	}

	const getData = (param) => {
		console.log(param);
		let url = proxy.$config.baseUrl;
		let params = {
			loading: false,
			url: '/webapi/eidData.ashx?oper=LTTG_Multifunction',
			method: 'get',
			data: param
		}
		return new Promise((resolve, reject) => {
			try {
				proxy.$api.getData(url, params).then((res) => {
					console.log(res);
					if (res.status == '1') {
						resolve(res);
					} else {
						reject('获取信息失败' + res.msg)
					}
				})
			} catch (e) {
				console.log(e)
				reject(false);
			}
		})
	}

	const getJoinData = (param) => {
		console.log(param);
		let url = proxy.$config.baseUrl;
		let params = {
			loading: false,
			url: '/' + _site + '/webapi/eidData.ashx?oper=LTTG_Multifunction',
			method: 'get',
			data: param
		}
		console.log(url, _site)
		return new Promise((resolve, reject) => {
			try {
				proxy.$api.getData(url, params).then((res) => {
					// console.log(res);
					if (res.status == '1') {
						resolve(res);
					} else {
						reject('获取信息失败' + res.msg)
					}
				})
			} catch (e) {
				console.log(e)
				reject(false);
			}
		})
	}
	const delParaUrl = () => {
		// 获取当前页面的URL
		let currentUrl = window.location.href;
		// 使用正则表达式将参数部分移除
		let updatedUrl = currentUrl.replace(/[?&].*$/, '');

		// 使用JavaScript来更新URL
		history.replaceState({}, '', updatedUrl);
		return;
		// 要删除的参数名
		let paramToRemove = 'paramNameToRemove';

		// 使用正则表达式来匹配并移除参数
		// let updatedUrl = currentUrl.replace(new RegExp('[?&]' + paramToRemove + '=[^&]*'), '');

		// 如果参数位于URL的末尾，也需要处理
		updatedUrl = updatedUrl.replace(new RegExp(paramToRemove + '=[^&]*&'), '');

		// 如果URL以被移除的参数结尾，去掉末尾的&符号
		updatedUrl = updatedUrl.replace(/[?&]$/, '');

		// 使用JavaScript来更新URL
		history.replaceState({}, '', updatedUrl);
	}
	const appslogan = computed(() => {
		console.log(proxy.$config.appslogan)
		return proxy.$config.appslogan
	})

	const appVersion = computed(() => {
		return proxy.$config.version
	})

	// 监听倒计时变化
	watch(countdown, (newValue, oldValue) => {
		if (newValue === 0) {
			// 倒计时结束时执行相应逻辑
			// clearInterval(timerId);
		}
	});
	/*
	 --用户授权登录后监测是否是邀请状态
	 --监听用户身份信息更新，解决微信小程序app.js和index未按顺序执行的问题
	*/
	watch(() => UserStore.member.member_id, (newVal, oldVal) => {
		console.log("用户数据变化", UserStore.member)
		proxy.$utils.timerout(() => {
			// #ifdef APP-PLUS || MP-WEIXIN
			// if (UserStore.islogin)
			// --enterSystem(true);
			// #endif
		}, 250)
	})

	onMounted(async (options) => {
		console.log("onMounted")
		// #ifdef MP-WEIXIN
		wx.showShareMenu({
			withShareTicket: true,
			//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
			menus: ["shareAppMessage", "shareTimeline"]
		})
		// #endif
		// 组件挂载时启动计时
		if (!UserStore.islogin) return;
	});
	// 统一跳转接口，拦截未登录路由
	const to = (url, bool) => {
		console.log(url)
		if (!url) {
			proxy.$utils.msg("该功能暂未开通");
			return;
		}
		// if (!UserStore.member.islogin) {
		// 	proxy.$utils.tologin()
		// 	return;
		// }
		if (bool) {
			if (!UserStore.member.isTesters) {
				proxy.$utils.msg("该功能暂对测试人员开通");
				return;
			}
		}
		uni.navigateTo({
			url
		});
	}

	const clear = () => {
		proxy.$utils.alert('确定要清除本地缓存数据吗？', () => {
			uni.clearStorageSync();
			UserStore.logout();
			try {
				webSite.value = [];
				uni.removeStorageSync('use_member_list');
				uni.removeStorageSync('usemall_member');
			} catch (e) {
				// error
			}
		})
	}
	//-- 微信分享实际操作

	let shareImg = '../../static/logo.png';
	onShareAppMessage((res) => {
		console.log(res)
		if (res.from === 'button') {
			// 来自页面内分享按
			return {
				title: proxy.$config.appslogan,
				path: '/pages/tabbar/launch',
				imageUrl: shareImg,
				success: function(res) {
					// 转发成功
					proxy.$utils.msg('转发成功~');
				},
				fail: function(res) {
					// 转发失败
					proxy.$utils.msg('转发失败~');
				}
			};
		} else {
			return {
				title: proxy.$config.appslogan,
				path: '/pages/tabbar/launch',
				imageUrl: shareImg,
				success: res => {
					proxy.$utils.msg('转发成功~');
				},
				fail: err => {
					proxy.$utils.msg('转发失败~');
				}
			};
		}
	})
	onShareTimeline(() => {
		return;
		return {
			title: '聚友大道--聚管事',
			query: 'share=', // 可不填 传递的参数，只能是这种格式
			imageUrl: urlImg
		}
	})
</script>

<style lang="scss">
	page,
	.page-container {
		background: $uni-bg-color-grey;
	}

	.panel-bg {
		image {
			width: 100%;
			height: 100%;
		}
	}

	/* 授权登录 */
	.home-area {
		.header {
			padding: 30rpx 50rpx;
			text-align: center;
			min-height: 300rpx;
			position: relative;

			.header .h2 {
				display: block;
				height: 50px;
				line-height: 50px;
				font-size: 1.25rem;
			}

			.header image {
				width: 270rpx;
				height: 270rpx;
			}
		}

		.content {
			padding: 20px 15px;

			.h3 {
				padding: 5px 5px;
				display: block;
				color: #2c2a2a;
				font-size: 1.25rem;
			}

			text {
				display: block;
				color: #9d9d9d;
				margin-top: 40rpx;
			}
		}

		.btns {
			width: 100%;
			margin: 0 auto;
			position: fixed;
			bottom: 15px;
			left: 0;

			.clause {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 10px 0;

				.checkbox {
					width: 18.5px;
					height: 18.5px;
					border-radius: 50%;
					border: 1px solid rgb(167, 164, 164);
					margin-right: 5px;

					.icon {
						width: 100%;
						height: 100%;
					}
				}

			}

			.button {
				border-radius: 60rpx;
				margin: 10rpx auto;
				font-size: 0.95rem;
				width: 75%;
				font-weight: 250;
				height: 45px;
				line-height: 45px;
			}

			.button[type=primary] {
				border: 1px solid #d1d1d1;
				background-color: #0c0c0c;
				color: #fff;
			}

			.button.default {
				border: none 0;
				display: block;
				background-color: transparent;
				color: rgb(3, 46, 165);
				text-align: center;
			}
		}
	}
</style>